import React, { useState, useEffect } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Divider, Grid, Button } from '@material-ui/core';
import { Section, SectionAlternate } from 'components/organisms';

import {
  Webinars,
  Hero,
} from './components';

import { useDispatch, useSelector } from 'react-redux';
import { callGetApi } from 'utils/networking';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';

const useStyles = makeStyles(theme => ({
  pagePaddingTop: {
    paddingTop: theme.spacing(3),
    [theme.breakpoints.up('md')]: {
      paddingTop: theme.spacing(5),
    },
  },
  sectionAlternate: {
    background: 'transparent',
    backgroundImage: `linear-gradient(180deg, ${theme.palette.background.paper} 40%, ${theme.palette.primary.dark} 0%)`,
  },
}));

const Artists = () => {
  const classes = useStyles();
  const dispatch = useDispatch();
  const history = useHistory();

  const searchKeyword = useSelector((state) => state.searchArtists.searchKeyword)
  const [artistList, setArtistList] = useState([]);

  useEffect(() => {
    loadData();
  }, [searchKeyword])

  const loadData = async () => {
    callGetApi(`song/search_top_artists?search_key=${searchKeyword}&limit=24&offset=0`, dispatch, (data) => {
      setArtistList(data.data)
    })
  }

  const loadMoreData = async () => {
    callGetApi(`song/search_top_artists?search_key=${searchKeyword}&limit=24&offset=${artistList.length}`, dispatch, (data) => {
      const newList = [...artistList, ...data.data];
      setArtistList(newList)
    })
  }

  return (
    <div>
      <Hero />
      <Divider />
      <Section style={searchKeyword && artistList.length > 6 ? { 'maxWidth': '100%' } : {}}>
        {searchKeyword ? (
          <>
            <Webinars data={artistList} />
            {artistList.length % 24 == 0 && (
              <Grid item xs={12} container justifyContent="center" className={classes.loadMoreButton}>
                <Button
                  variant="contained"
                  color="primary"
                  size="large"
                  onClick={loadMoreData}
                  className={classes.button}
                >
                  Load more
                </Button>
              </Grid>
            )}
          </>
        ) : (
          <Webinars data={artistList.slice(0, 6)} />
        )}
        <div className={classes.loadMore}>
        </div>
      </Section>
    </div>
  );
};

export default Artists;
